import React, { useRef, useEffect, useState } from 'react';
import { Spin } from 'antd';

import {
  ProFormText,
  ProFormTextArea,
  ProFormSelect,
  ProFormRadio,
  ModalForm,
  ModalFormProps,
  ProFormDigit,
  ProFormInstance,
  ProFormList,
  ProFormDependency,
} from '@ant-design/pro-form';
import { services } from '@/network/api';
import utils from '@/utils/index';

export type formProps = {
  id?: number;
  busType?: any;
  _onFinish?: Function;
};

const TableForm: React.FC<ModalFormProps & formProps> = (props) => {
  const { visible, id, busType, _onFinish, ...restProps } = props;

  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };
  const formRef = useRef<ProFormInstance<any>>();
  const [spinning, setSpinning] = useState(false);

  useEffect(() => {
    const getField = async () => {
      setSpinning(true);
      if (id && visible) {
        let res = await services.getField({ id });
        !!res?.data?.fieldOption && (res.data.fieldOption = JSON.parse(res?.data?.fieldOption));
        formRef.current?.setFieldsValue(res.data);
      } else {
        formRef.current?.resetFields();
        formRef.current?.setFieldsValue({ busType });
      }
      setSpinning(false);
    };
    getField();
  }, [id, busType, visible]);

  const onFinish = async (values: any) => {
    const { fieldOption, ...restVlaues } = values;
    restVlaues.fieldOption = JSON.stringify(fieldOption);
    await services.saveField(restVlaues);
    _onFinish?.();
  };
  return (
    <>
      <ModalForm
        {...restProps}
        formRef={formRef}
        title={id ? '编辑字段' : '新建字段'}
        width="500px"
        visible={visible}
        onFinish={onFinish}
        initialValues={{
          isDefault: 0,
          isRequire: 0,
          isEnable: 1,
          order: 0,
          multiple: 0,
          dateType: 'date',
        }}
        layout="horizontal"
        {...formItemLayout}
      >
        <Spin spinning={spinning}>
          <div className="hide">
            <ProFormDigit label="字段id" name="id" fieldProps={{ precision: 0, disabled: true }} />
          </div>
          <ProFormSelect
            label="字段归属"
            disabled
            name="busType"
            rules={[
              {
                required: true,
                message: '请选择字段归属',
              },
            ]}
            options={[
              { label: '用户', value: 1 },
              { label: '线索', value: 2 },
              { label: '客户', value: 3 },
            ]}
          />
          <ProFormDependency name={['isDefault']}>
            {(dep) => {
              if (dep?.isDefault === 1) {
                return (
                  <ProFormText
                    label="字段名称"
                    rules={[
                      {
                        required: true,
                        message: '请输入字段名称',
                      },
                    ]}
                    name="name"
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormText
            label="字段标签"
            rules={[
              {
                required: true,
                message: '请输入字段标签',
              },
            ]}
            name="label"
          />
          <ProFormDigit
            label="字段顺序"
            name="order"
            rules={[
              {
                required: true,
                message: '请输入字段顺序',
              },
            ]}
            fieldProps={{ precision: 0 }}
          />

          <ProFormRadio.Group
            name="isDefault"
            label="是否默认"
            rules={[
              {
                required: true,
                message: '请选择是否默认',
              },
            ]}
            options={[
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ]}
          />
          <ProFormRadio.Group
            name="isRequire"
            label="是否必填"
            rules={[
              {
                required: true,
                message: '请选择是否必填',
              },
            ]}
            options={[
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ]}
          />
          <ProFormRadio.Group
            name="isEnable"
            label="是否启用"
            rules={[
              {
                required: true,
                message: '请选择是否启用',
              },
            ]}
            options={[
              { label: '是', value: 1 },
              { label: '否', value: 0 },
            ]}
          />
          <ProFormTextArea label="备注" name="describe" />
          <ProFormText label="输入提示" name="placeholder" />
          <ProFormDependency name={['isDefault']}>
            {(dep) => {
              if (dep?.isDefault !== 1 || true) {
                return (
                  <ProFormSelect
                    label="字段类型"
                    name="fieldType"
                    rules={[
                      {
                        required: true,
                        message: '请选择字段归属',
                      },
                    ]}
                    options={utils.constant.FORM_TYPE_LIST.toGroupOption()}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.regEx) {
                return (
                  <ProFormSelect
                    label="字段正则"
                    name="regEx"
                    rules={[]}
                    options={utils.constant.REG_EX_LIST.toOption()}
                    placeholder="可选字段正则"
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.max) {
                return (
                  <ProFormDigit
                    // initialValue={undefined}
                    label={utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.max || '字段最大长度'}
                    name="max"
                    rules={[]}
                    fieldProps={{ precision: 0 }}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.min) {
                return (
                  <ProFormDigit
                    // initialValue={''}
                    label={dep?.fieldType === 2 ? '最小值' : '字段最小长度'}
                    name="min"
                    rules={[]}
                    fieldProps={{ precision: 0 }}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.precision) {
                return (
                  <ProFormDigit
                    label="精确度"
                    name="precision"
                    rules={[]}
                    fieldProps={{ precision: 0 }}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.fieldOption) {
                return (
                  <ProFormList
                    label="字段选项"
                    name="fieldOption"
                    creatorButtonProps={{
                      position: 'bottom',
                      creatorButtonText: '添加选项',
                    }}
                    creatorRecord={{
                      value: '',
                    }}
                  >
                    {(f, index: number, action) => {
                      // console.log(f, index, action);
                      return (
                        <>
                          {`选项${index + 1}`}
                          <ProFormText name="label" placeholder="请输入选项标签" />
                          {/* <ProFormText name="value" placeholder="请输入选项值" /> */}
                        </>
                      );
                    }}
                  </ProFormList>
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.multiple) {
                return (
                  <ProFormRadio.Group
                    name="multiple"
                    label="是否多选"
                    options={[
                      { label: '是', value: 1 },
                      { label: '否', value: 0 },
                    ]}
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
          <ProFormDependency name={['fieldType']}>
            {(dep) => {
              if (!!utils.constant.FORM_TYPE_LIST[dep?.fieldType]?.dateType) {
                return (
                  <ProFormSelect
                    label="时间控件类型"
                    name="dateType"
                    rules={[]}
                    options={utils.constant.DATE_TYPE_LIST.toOption()}
                    placeholder="可选时间控件类型"
                  />
                );
              }
              return <></>;
            }}
          </ProFormDependency>
        </Spin>
      </ModalForm>
    </>
  );
};

export default TableForm;
